package gat.application.tg.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bitsun.core.common.exception.AppException;
import com.bitsun.core.common.exception.ErrorCode;
import com.bitsun.core.common.persistence.BasePService;
import com.bitsun.core.common.persistence.IPService;
import com.bitsun.core.common.persistence.Pager;
import com.bitsun.core.common.persistence.QueryParamUtils;
import com.google.common.base.CaseFormat;
import gat.application.tg.TgBotService;
import gat.application.tg.UserBotService;
import gat.common.util.CurrentThread;
import gat.convertor.tg.TgBotReqDtoConvertor;
import gat.convertor.tg.TgBotResDtoConvertor;
import gat.dto.req.tg.TgBotReqDto;
import gat.dto.req.tg.TgBotReqParams;
import gat.dto.res.tg.TgBotResDto;
import gat.dto.res.tg.UserBotResDto;
import gat.infrastructure.persistence.dao.tg.TgBotMapper;
import gat.infrastructure.persistence.po.tg.TgBotPo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
 * 示例表，应用（业务编排）层实现
 * @author: yanshukeji-java
 * @email: yanshukeji-java
 */
@Slf4j
@Service("tgBotAppService")
@Transactional(rollbackFor = Exception.class)
public class TgBotServiceImpl implements TgBotService {

    @Autowired
    private TgBotReqDtoConvertor tgBotReqDtoConvertor;

    @Autowired
    private TgBotResDtoConvertor tgBotResDtoConvertor;

    @Autowired
    private UserBotService userBotService;

    private IPService<TgBotPo> tgBotPoService;

    @SuppressWarnings("SpringJavaAutowiringInspection")
    public TgBotServiceImpl(TgBotMapper tgBotMapper) {
        this.tgBotPoService = new BasePService(tgBotMapper);
    }



    @Override
    public TgBotResDto save(TgBotReqDto reqDto) {
        TgBotPo tgBotPo = tgBotPoService.getOne(new LambdaQueryWrapper<TgBotPo>()
                .eq(TgBotPo::getBotName, reqDto.getBotName())
        );
        if (tgBotPo != null) {
            throw new AppException("机器人已存在：" + reqDto.getBotName(), ErrorCode.pc("417"));
        }

        TgBotPo po = tgBotReqDtoConvertor.dto2Po(reqDto);
        tgBotPoService.save(po);
        TgBotResDto resDto = tgBotResDtoConvertor.po2Dto(po);
        return resDto;
    }

    @Override
    public boolean deleteByIds(String ids) {
        try {
            List<Long> idLongList =
            Arrays.asList(ids.split(",")).stream().map(s -> NumberUtils.createLong(s.trim())).collect(Collectors.toList());
            return tgBotPoService.removeByIds(idLongList);
        } catch (Exception e) {
            throw new AppException("参数错误：" + ids, ErrorCode.pc("417"), e);
        }
     }

    @Override
    public Pager<TgBotResDto> doPager(Map<String, Object> params) {
        Pager<TgBotPo> poPager = tgBotPoService.queryPage(params, TgBotPo.class);
        Pager<TgBotResDto> resDtoPager = tgBotResDtoConvertor.convertPoPager2ResDtoPager(poPager);
        return resDtoPager;
    }

    @Override
    public TgBotResDto selectOne(Long id) {
        TgBotPo po = tgBotPoService.getById(id);
        TgBotResDto resDto = tgBotResDtoConvertor.po2Dto(po);
        return resDto;
    }

    @Override
    public TgBotResDto selectOne(Map<String, Object> params) {
        QueryWrapper queryWrapper = QueryParamUtils.queryWrapper4eq(TgBotPo::new, params);
        queryWrapper.last(" limit 1");
        TgBotPo po = tgBotPoService.getOne(queryWrapper);
        TgBotResDto resDto = tgBotResDtoConvertor.po2Dto(po);
        return resDto;
    }

    @Override
    public boolean updateProps(Long id, Map<String, Object> params) {
        UpdateWrapper<TgBotPo> updateWrapper = QueryParamUtils.updateWrapper4Map(TgBotPo::new, id, params);
        return tgBotPoService.update(new TgBotPo(), updateWrapper);
        }

    @Override
    public boolean updateProps(Long id, TgBotReqDto reqDto) {
        TgBotPo po = tgBotReqDtoConvertor.dto2Po(reqDto);
        po.setId(id);
        return tgBotPoService.updateById(po);
    }


    @Override
    public boolean updateAllProps(Long id, TgBotReqDto reqDto) {
        UpdateWrapper<TgBotPo> updateWrapper = Wrappers.update();
        updateWrapper.eq("id", id);
        Field[] fields = TgBotReqDto.class.getDeclaredFields();
        Arrays.stream(fields).filter(f -> !Modifier.isStatic(f.getModifiers())).forEach(field -> {
        try {
        PropertyDescriptor propertyDescriptor = new PropertyDescriptor(field.getName(), TgBotReqDto.class);
        Method getMethod = propertyDescriptor.getReadMethod();
        String fileNameCamel = getMethod.getName().substring(3);
        String fileNameUnderline = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, fileNameCamel);
        updateWrapper.set(fileNameUnderline, getMethod.invoke(reqDto));
        } catch (Exception ex) {
        log.warn("属性不存在get方法："+field.getName(),ex);
        }
        });
        return tgBotPoService.update(new TgBotPo(), updateWrapper);
    }

    @Override
    public TgBotResDto getTgBotByBotUni(String botId) {
        TgBotPo tgBotPo = tgBotPoService.getOne(new LambdaQueryWrapper<TgBotPo>().eq(TgBotPo::getBotName, botId));
        return tgBotResDtoConvertor.po2Dto(tgBotPo);
    }

    @Override
    public Pager<TgBotResDto> queryPage(TgBotReqParams params) {
        IPage<TgBotPo> iPage =
                tgBotPoService.page(new Page<>(params.getCurrentPage(), params.getPageSize()),
                        new LambdaQueryWrapper<TgBotPo>()
                                .like(StringUtils.isNotBlank(params.getBotName()), TgBotPo::getBotName, params.getBotName())
                                .like(StringUtils.isNotBlank(params.getNickName()), TgBotPo::getNickName, params.getNickName())
                                .eq(StringUtils.isNotBlank(params.getPayAddress()), TgBotPo::getPayAddress, params.getPayAddress())
                                .eq(ObjectUtil.isNotEmpty(params.getBotStatus()), TgBotPo::getBotStatus, params.getBotStatus())
                                .like(StringUtils.isNotBlank(params.getToken()), TgBotPo::getToken, params.getToken())
                                .orderByDesc(TgBotPo::getCreateTime)

                );
        return tgBotResDtoConvertor.convertPoPager2ResDtoPager(
                new Pager<>(iPage.getRecords(), iPage.getTotal(), params.getPageSize(), iPage.getCurrent()));
    }

    @Override
    public List<TgBotResDto> queryList() {
        String username = CurrentThread.getCurrentUser().getUsername();
        if (!StringUtils.equals(username, "admin")) {

            UserBotResDto userBotResDto = userBotService.getUserBotByUserCode(CurrentThread.getCurrentUser().getUserCode());
            if (userBotResDto != null ) {
                TgBotPo tgBotPo = tgBotPoService.getOne(new LambdaQueryWrapper<TgBotPo>()
                        .eq(TgBotPo::getBotName, userBotResDto.getBotId())
                );
                TgBotResDto tgBotResDto = tgBotResDtoConvertor.po2Dto(tgBotPo);
                List<TgBotResDto> resDto = new ArrayList<>();
                resDto.add(tgBotResDto);
                return resDto;
            }
        }

        return tgBotPoService.list(new LambdaQueryWrapper<TgBotPo>()
                .eq(TgBotPo::getBotStatus, 1)
        ).stream().map(tgBotResDtoConvertor::po2Dto).collect(Collectors.toList());
    }

}